<template>
  <view>
    <view class="list-container">
      <!-- 检查信息 -->
      <view class="item">
        <view class="top-label" @click="retract(1)">
          <view>检查信息</view>
          <view v-if="showBasicInformation[1].show"><uv-icon name="arrow-down" size="40rpx" color="#000000"></uv-icon></view>
          <view v-else><uv-icon name="arrow-right" size="40rpx" color="#000000"></uv-icon></view>
        </view>
        <view class="info" v-if="showBasicInformation[1].show">
          <view class="row">
            <view class="title">检查地点:</view>
            <view class="con">{{ formData.canteenName?formData.canteenName:formData.schoolName }}</view>
          </view>
          <view class="row">
            <view class="title">指标名称:</view>
            <view class="con">{{ formData.targetName }}</view>
          </view>
          <view class="row">
            <view class="title">检查日期:</view>
            <view class="con">{{ formData.lawDate }}</view>
          </view>
          <view class="row row-check">
            <view class="title">检查人 <span style="color: rgba(229,16,16,0.71)">*</span>:</view>
            <view class="" @click="toSelectExaminer" style="display: flex; color: #3d3d3d">
              <view v-for="(item, index) in formData.userNameList" :key="index" v-if="formData.userNameList">
                <view v-if="index < 2">{{ item }}<span v-if="formData.userNameList.length > 1 && index == 0">，</span></view>
              </view>
              <view v-if="!formData.userName">请选择</view>
              <span v-if="formData.userNameList && formData.userNameList.length > 2">等{{ formData.userNameList.length }}人</span>
              <uv-icon name="arrow-right" size="20rpx" color="#000000"></uv-icon>
            </view>
          </view>
        </view>
      </view>
      <!-- 检查内容 -->
      <view class="item">
        <view class="top-label" @click="retract(2)">
          <view>检查内容</view>
          <view v-if="showBasicInformation[2].show"><uv-icon name="arrow-down" size="40rpx" color="#000000"></uv-icon></view>
          <view v-else><uv-icon name="arrow-right" size="40rpx" color="#000000"></uv-icon></view>
        </view>
        <view class="info">
            <DaTree
                v-show="showBasicInformation[2].show"
                ref="DaTreeRef"
                :data="formData.lawBindEntryList"
                labelField="content"
                valueField="id"
                defaultExpandAll
                :show-annotation="true"
                :show-control="false"
                :defaultCheckedKeys="defaultCheckedKeysValue"
                @getProblemLen="getProblemLen"
            >
            </DaTree>
        </view>
      </view>
      <!-- 检查照片 -->
      <view class="item">
        <view class="top-label">
          <view class="check-all">
            <view class="requireStar">检查照片</view>
            <view class="check-all-ri-label">至少上传3张图片</view>
            <view class="zi-label" style="width: 25%;text-align: end;">{{ imageLength}} / 30</view>
          </view>
        </view>
        <view class="info" style="display: flex">
          <view class="file-all">
            <fileUpload :tableId="formData.rowId" tableName="sup_law_item" type="photo" :watermarkFlag="true" :place="userInfo.user.org ?  userInfo.user.org.orgName : ''"
                        :maxCount="30" multiple :deletable="true" @imageListArray="imgList" @delImageListArray="delImgList"
                        @initImage="initImage" width="72" height="72">
            </fileUpload>
          </view>
        </view>
      </view>
      <!-- 检查记录单 -->
      <view class="item">
        <view class="top-label">
          <view>检查记录单</view>
          <view class="zi-label">{{ imageRecordLength}} / 3</view>
        </view>
        <view class="info" style="display: flex">
          <view class="file-all">
            <fileUpload :tableId="formData.rowId" tableName="sup_law_item" type="bill" :watermarkFlag="true"
                        :maxCount="3" multiple :deletable="true" @imageListArray="imgRecordList" @delImageListArray="delRecordImgList"
                        @initImage="initRecordImage" width="72" height="72">
            </fileUpload>
          </view>
        </view>
      </view>
      <!-- 检查情况补充 -->
      <view class="item">
        <view class="top-label">
          <view>检查情况补充</view>
        </view>
        <view class="infoTextArea">
          <uv-textarea v-model="formData.lawItem.checkRecord" count placeholder="请输入内容"></uv-textarea>
          <view class="fontCount" @click="showSpeechRecord">
            <image :src="imgMinioPath + '/law/yuyin.png'"></image>
          </view>
        </view>
      </view>
      <!-- 是否需要整改 -->
      <view class="item">
        <view class="top-label">
          <view class="requireStar"  style="width: 35%">是否需要整改</view>
          <view class="rectification">
            <view v-for="(item, index) in rectificationList" :key="index" @click="selectRectification(index)">
              <view :class="formData.rectifyFlag == index ? 'rectification-item-action' : 'rectification-item'">{{ item.name }}</view>
            </view>
          </view>
        </view>
        <view v-if="formData.rectifyFlag == 1" class="info">
          <view class="row">
            <view class="zheng-gai-zi requireStar">整改日期</view>
            <view class="con select-right" @click="open">
              <span v-if="!showDate">请选择整改日期</span>
              <span v-else>{{ formData.lawItem.deadlineDate }}</span>
            </view>
          </view>
          <view class="">
            <view style="display: flex; flex-direction: column">
              <view class="zheng-gai-zi requireStar">整改意见</view>
              <view class="zi-bottom">
                以上检查出的<view class="green-content">{{ problemLen }}</view>项问题由<view class="green-content">{{userInfo.user.org?userInfo.user.org.orgName:'--'}}</view>负责督促整改验收，学校于<view class="blue-content">{{formData.lawItem.deadlineDate?formData.lawItem.deadlineDate:'xx-xx-xx' }}</view>前完成整改并上报。
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 检查人签名 -->
      <view class="item" style="margin-bottom: 200rpx">
        <view class="top-label">
          <view class="requireStar">检查人签名</view>
          <image v-if="formData.superviseSign" class="img-sign" :src="formData.superviseSign" @tap="isCanvas=true"/>
          <uv-input v-else border="none" disabled disabledColor="rgba(0,0,0,0)" inputAlign="right"
                    suffix-icon="arrow-right" placeholder="请设置电子签名" @tap="isCanvas=true"></uv-input>
        </view>
      </view>
    </view>
    <view class="check-bottom-box" @click.stop>
      <button class="sure-button" @click.stop="submit()">确认</button>
    </view>
    <uv-popup ref="refSpeech" mode="bottom" round="8" @change="change">
      <speech-recognition @getSpeeckInfo="getSpeeckInfo" :maxlength="140" v-if="refSpeechShow"></speech-recognition>
    </uv-popup>
    <!-- 日期选择 -->
    <uv-datetime-picker ref="datetimePicker" :minDate="formData.lawDate" v-model="deadlineDate" mode="date" :formatter="formatter" @confirm="confirm"></uv-datetime-picker>
    <!-- 签名 -->
    <drawSign v-model="isCanvas" @complete="getSign" canvasId="isCanvas" tableName="sup_law" tableType="sup_law"/>
  </view>
</template>

<script setup>
import {ref, reactive, getCurrentInstance, defineProps} from 'vue';
const {proxy} = getCurrentInstance();
import targetAPI from "@/api/law/target/target";
import supTaskAPI from "@/api/law/supTask/supTask";
import signatureApi from '@/api/school/signature/signature';
import drawSign from '@/componentsTool/draw-sign/sign.vue'
import supLawApi from "@/api/law/supLaw/supLaw";
import config from "@/common/config";
let imgMinioPath = ref(config.IMG_MINIO_PATH);

const userInfo = ref(uni.getStorageSync('userInfo'));
//
let isCanvas = ref(false);

const DaTreeRef = ref()

const defaultCheckedKeysValue = ref([])

// 图片长度
const imageLength = ref(0);

const imageRecordLength = ref(0);
const props = defineProps({
  checkInformation:{
    type:Object,
    default:{},
    required:true,
  }
});
let formData = reactive({
  entryType:uni.getStorageSync('entryType'),
  lawDate: proxy.dayjs().format('YYYY-MM-DD'),
  lawType:"1",
  sourceType:'',
  rectifyFlag:0,
  lawBindEntryList:[],
  fileList:[],
  userNameList:[],
  fileRecordList:[],
  lawItem:{
    checkRecord:'',
    fileList:[],
    userId:'',
    userName:'',
    deadlineDate:null,
    rectificationContent:'',
  },
  userId:'',
  userName:'',
  superviseSign:'',
})
// 整改意见
const showBasicInformation = reactive([{ show: true }, { show: true }, { show: true }, { show: true }, { show: true }]);
const value = ref('');
// 收起放开
function retract(index) {
  showBasicInformation[index].show = !showBasicInformation[index].show;
}
//整改
const rectificationList = ref([
  { name: '否', value: 0 },
  { name: '是', value: 1 }
]);

const deadlineDate = ref(Number(new Date()));

let datetimePicker = ref();

const isActive = ref(-1);
function annotationShow(index) {
  if (isActive.value === index) {
    isActive.value = -1;
  } else {
    isActive.value = index;
  }
}
//问题长度
let problemLen = ref(0);
function getProblemLen(e){
  if(e){
    problemLen.value = e.filter(item => item.note).length;
  }
}
function selectRectification(index) {
  formData.rectifyFlag = index;
  if(index==1){
    getProblemLen();
    formData.lawItem.rectificationContent=`以上检查出的${problemLen.value}项问题由${userInfo.value.user.org?userInfo.value.user.org.orgName:'--'}负责督促整改验收，学校于${formData.lawItem.deadlineDate?formData.lawItem.deadlineDate:'xx-xx-xx'}前完成整改并上报。`;
  }else{
    formData.lawItem.rectificationContent="";
  }
}
function setRectificationContent(){
  if(formData.lawItem.rectificationContent){
    formData.lawItem.rectificationContent=`以上检查出的${problemLen.value}项问题由${userInfo.value.user.org?userInfo.value.user.org.orgName:'--'}负责督促整改验收，学校于${formData.lawItem.deadlineDate?formData.lawItem.deadlineDate:'xx-xx-xx'}前完成整改并上报。`;
  }
}
// 打开选择日期组件
function open() {
  datetimePicker.value.open();
}
const showDate = ref(false);
// 选择日期
function confirm(e) {
  formData.lawItem.deadlineDate =  proxy.dayjs(e.value).format('YYYY-MM-DD');
  //设置模板参数
  setRectificationContent();
  showDate.value = true;
}
// 日期格式化
function formatter(type, value) {
  if (type === 'year') {
    return `${value}年`;
  }
  if (type === 'month') {
    return `${value}月`;
  }
  if (type === 'day') {
    return `${value}日`;
  }
  return value;
}

/**初始化图片*/
let initRecordImage = (imageList) => {
  imageRecordLength.value = imageList.length;
};

/** 上传图片 **/
let imgRecordList = (addList, imageList)=>{
  formData.fileRecordList = addList;
  imageRecordLength.value = imageList.length;
}

/** 删除图片 **/
let delRecordImgList = (delFileIds, imageList) => {
  formData.delRecordFileIds = delFileIds;
  imageRecordLength.value = imageList.length;
};

// 选择检查人
const toSelectExaminer = (e) => {
  let data = {
    checkboxValue: formData.userId ? formData.userId : '',
    schoolId:formData.schoolId
  };
  uni.navigateTo({
    url: '/packageLawEnforcement/pages/startCheck/selsectExaminer?data=' + encodeURIComponent(JSON.stringify(data)),
    success: () => {
      // 在添加列表判断是否刷新页面
      //监听事件
      uni.$once("selsectExaminer", (data) => {
        if (data && data.length > 0) {
          formData.userId = data.map((item) => item.userId);
          formData.userName = data.map((item) => item.userName);
          formData.userNameList = formData.userName;
          formData.lawItem.userId = formData.userId.join(',');
          formData.lawItem.userName = formData.userName.join(',');
        } else {
          formData.userId = '';
          formData.userName = '';
          formData.userNameList = [];
          formData.lawItem.userId = '';
          formData.lawItem.userName = '';
        }
      });
    }
  });
}

let initImage = (imageList) => {
  imageLength.value = imageList.length;
};

/** 上传图片 **/
let imgList = (addList, imageList)=>{
  formData.fileList = addList;
  imageLength.value = imageList.length;
  //设置模板参数
  setRectificationContent();
}

/** 删除图片 **/
let delImgList = (delFileIds, imageList) => {
  formData.delFileIds = delFileIds;
  imageLength.value = imageList.length;
};

/** 初始化数据 */
let getTargetList = async (e) => {
  let res = await proxy.http.asyncGet(targetAPI.targetQuery(formData.targetId));
  console.log(res)
  if (res.code === 0) {
    formData.lawBindEntryList=[...res.data.entryList];
  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
};

let getTaskTargetList = async (e) => {
  let res = await proxy.http.asyncGet(supTaskAPI.targetQuery(props.checkInformation.taskId));
  if (res.code === 0) {
    formData.lawBindEntryList=[...res.data.entryList];
  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
};
//获取签名
let getSign = e => {
  formData.superviseSign = e;
}

/** 获取签名功能 */
let getSignData = async (e) => {
  let res = await proxy.http.asyncPost(signatureApi.getPubSignature,{tableName: 'sup_law', tableType: 'sup_law'});
  if (res.code === 0) {
    if(res.data) {
      formData.superviseSign = res.data.personSign;
    }
  }
}

//语音输入
const refSpeech = ref();



const showSpeechRecord = () => {
  refSpeech.value.open();
};

function getSpeeckInfo(val) {
  refSpeech.value.close();
  formData.lawItem.checkRecord += val;
}
const refSpeechShow = ref(false);
const change= (e) => {
  refSpeechShow.value=e.show
}
// 开始检查确认按钮
async function submit(){
  if (!formData.userName) {
    uni.showToast({
      icon: 'none',
      title: '请选择检查人'
    });
    return;
  }
  if (imageLength.value < 3) {
    uni.showToast({
      icon: 'none',
      title: '请至少上传3张检查照片'
    });
    return;
  }
  if(formData.rectifyFlag == 1 && !formData.lawItem.deadlineDate){
    uni.showToast({
      icon: 'none',
      title: '请选择整改截至日期'
    });
    return;
  }
  if (!formData.superviseSign) {
    uni.showToast({
      icon: 'none',
      title: '签名不能为空'
    });
    return;
  }
  setRectificationContent();
  //获取树信息
  formData.lawBindEntryList =  DaTreeRef.value.handleTextAll()
  //拼装数据
  formData.lawItem.fileList=[...formData.fileList, ...formData.fileRecordList];
  formData.userId = formData.lawItem.userId;
  formData.userName =formData.lawItem.userName;
  let res = await proxy.http.asyncPost(supLawApi.getsupLawAdd, formData);
  if (res.code === 0) {
    await uni.showToast({icon: 'success', title: '添加成功', duration: 2000});
    setTimeout(() => {
       goBack();
    }, 1000)
  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
};

/** 返回上一页 */
let goBack = async () => {
  uni.$emit("refresh", {});
  await uni.navigateBack({
    delta: 2
  });
};

onMounted(() => {
  if(props.checkInformation.hasOwnProperty("canteenId")){
    formData.canteenId =props.checkInformation.canteenId
    formData.canteenName =props.checkInformation.canteenName
  }
  if(props.checkInformation.hasOwnProperty("schoolId")){
    formData.schoolId =props.checkInformation.schoolId
    formData.schoolName =props.checkInformation.schoolName
  }
  if(props.checkInformation.hasOwnProperty("targetId")){
    formData.targetId =props.checkInformation.targetId
    formData.targetName =props.checkInformation.targetName
  }
  if(props.checkInformation.hasOwnProperty("lawType")){
    formData.lawType =props.checkInformation.lawType
  }
  formData.sourceType=formData.entryType!='6'?'02':'03'
  if (formData.lawType === '2'){
      formData.targetId =props.checkInformation.taskId
      formData.targetName =props.checkInformation.taskTargetName
      getTaskTargetList();
  }else {
      getTargetList();
  }
  getSignData();
});
</script>

<style lang="scss" scoped>
@import '@/static/css/dailycheck/viewIndex.scss';
@import '@/static/css/dailycheck/common.scss';

::v-deep .speech-main {
  .content {
    .uv-textarea__field {
      text-align: left !important;
      height: 400px !important;
    }
    .uv-border {
      border: 0 !important;
    }
  }
}
.row-check {
  display: flex;
  justify-content: space-between;
}
.textAreaBox {
  position: relative;
}

::v-deep .placeholder-color {
  color: rgba(0, 0, 0, 0.3);
  font-size: 32rpx;
}
::v-deep .requireStar {
  width: 30%;
}
::v-deep .requireStar:after {
  vertical-align: bottom; //加上星号会上下居中，不加会在上角展示
  content: ' *';
  color: rgba(255, 59, 48, 1);
  font-size: 100%;
}
::v-deep .requireStarBottom {
  width: 30%;
  position: relative;
}
::v-deep .requireStarBottom:after {
  position: absolute;
  right: 0;
  vertical-align: bottom; //加上星号会上下居中，不加会在上角展示
  content: ' *';
  color: rgba(255, 59, 48, 1);
  font-size: 100%;
}
.rectification {
  display: flex;
  grid-gap: 20rpx;
  .rectification-item-action {
    width: 82rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    background-color: rgba(51, 117, 246, 0.698);
    border-radius: 2px;
    font-size: 24rpx;
  }
  .rectification-item {
    background: #cccccc;
    @extend .rectification-item-action;
  }
}
.select-right {
  text-decoration: underline;
  font-size: 32rpx;
  color: #3375f6 !important;
}
.zi-bottom {
  color: #676767;
  margin-top: 20rpx;
}
.popup-title-1 {
  height: 112rpx;
  text-align: center;
  font-weight: bold;
  border-bottom: 1px solid #e7e7e7;
  line-height: 112rpx;
  background: #ffffff;
}
.up-popup-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 360rpx;
  background: #f5f5f5;
  .select-one {
    height: 110rpx;
    background: #ffffff;
    margin-top: -140rpx;
    text-align: center;
    border-bottom: 1px solid #e7e7e7;
    line-height: 110rpx;
  }
  .select-two {
    height: 110rpx;
    line-height: 110rpx;
    background: #ffffff;
    text-align: center;
    border-bottom: 1px solid #e7e7e7;
  }
  .bottom-box {
    height: 110rpx;
    line-height: 110rpx;
    background: #ffffff;
    text-align: center;
  }
}
.check-all {
  display: flex;
  width: 100%;
  align-items: center;
}
.check-all-ri-label {
  color: #9e9e9e;
  font-size: 24rpx;
  width: 60%;
}
.zi-label {
  color: #9e9e9e;
  font-size: var(--uni-font-size-14);
}
.file-img {
  width: 140rpx;
  height: 140rpx;
  border-radius: 4px;
  margin-left: 10rpx;
}
.file-all {
  display: flex;
  flex-wrap: wrap;
  grid-gap: 10rpx;
}
.delet-img{
  height: 32rpx;
  width: 32rpx;
  position: absolute;
  right: 0;
  top: 0;
}
.green-content {
  color: #27B3AA;
  display: inline;
}
.blue-content {
  color: #3375F6;
  display: inline;
  text-decoration: underline;
}
</style>
